
/*
	EVENTS (customizable):

		submit_callback: is triggered to collect the results of the submitted request

	EVENTS (triggable only):
		request_submit: force submit of the request

	INTERFACES:
		formSubmitInit: initialize the mechanism

	Trigger the request_submit event to process the request
	mode: json or the ID which will be recipient of the HTML requets output
*/

(function($){

var
	chainTrigger = function(e){
		var me = e.data;
		if ( $(this).uploaderUploaded() ){
			me.trigger("request_submit");
		}
		else
			alert("Failed to upload file!");
		return false;
	},

	submitUploadForms = function(me){
		var done = true;
		me.find('div.uploader').each(function(){
			if ( !$(this).uploaderUploaded() ){
				done = false;
				$(this).one("uploaded", me, chainTrigger );
				$(this).find(">form:first").trigger("submit");
			}
		});
		return done;
	},


	// We need first to process all "upload" forms inside, only after that we can actually fire the request
	collectForm = function(e){
		var  me=$(e.data), d=me.data("req_params");

		if ( submitUploadForms(me) ){
			// Reset all the included upload forms to not-uploaded status
			me.find('div.uploader').uploaderReset();

			// Populate d with the contents of all input-like controls
			me.find(':input[name!=][type!=checkbox]').each( function(){
				d[ $(this).attr("name") ] = $(this).val();
			});
			// We need to ensure that, for check and radio input, only selected ones are selected
			me.find(':input[name!=]:checked').each( function(){
				d[ $(this).attr("name") ] = $(this).val();
			});
			// Start request... (removed: $.param(d))
			me.jsonRequest( me.attr("req_id"),d,"form_results" );
		}
		return false;
	},

	getConfig = function($this){
		var c= $this.find(">input[type=hidden]:first").remove().val();
		if (c){
			return c.split("|");
		}else{
			return [false,false]
		}
	};

$.fn.formRequest = function( req_id, params, callback, callback_data ){
	return $(this).each(function(){
		// Setup request id
		$(this).attr("req_id", req_id );
		$(this).data("req_params", params );
		// then bind the special request_submit event which will fire form_collect when triggered
		$(this).bind('request_submit',this,collectForm);
		if ( callback ){
			$(this).bind('form_results', callback_data, callback );
		}
		// Now bind all the submit_buttons
		$(this).find(">button[name=request_submit]").bind("click", $(this),function(e){
														e.data.trigger("request_submit");
														return false;
													});
	});
};

Core.ObjectTypes["div.request"] = function(){
	var tmp=getConfig($(this)),
		callback = ( tmp[1] && Core.Callbacks[ tmp[1] ] ) ? Core.Callbacks[ tmp[1] ] : false;
	$(this).formRequest( tmp[0], {}, callback );
};


})(jQuery);

